package com.blink.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * <Description> </Description>
 * <ClassName> ZookeeperWatcher</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月12日 15:24
 */
public class ZookeeperWatcher implements Watcher {
    private static final Logger logger = LoggerFactory.getLogger(ZookeeperWatcher.class);
    private String zkName;
    private CountDownLatch countDownLatch;

    public ZookeeperWatcher(String zkName, final CountDownLatch countDownLatch) {
        this.zkName = zkName;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        logger.info("zkName:{},接收到事件：{}", zkName, watchedEvent);
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {
                logger.info("zkName:{},连接到zookeeper", zkName);
                countDownLatch.countDown();
            } else if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
                logger.info("zkName:{},节点发生变化，path:{}", zkName, watchedEvent.getPath());
            } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
                logger.info("zkName:{},节点数据发生变化，path:{}", zkName, watchedEvent.getPath());
            } else if (watchedEvent.getType() == Event.EventType.NodeCreated) {
                logger.info("zkName:{},节点创建，path:{}", zkName, watchedEvent.getPath());
            } else if (Watcher.Event.EventType.NodeDeleted == watchedEvent.getType()) {
                logger.info("zkName:{},节点删除，path:{}", zkName, watchedEvent.getPath());
            }
        }
    }
}
